package com.bw.spring.security.browser.authentication;

import com.bw.spring.security.core.validcode.ImageCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

public class ValidCodeFilter extends OncePerRequestFilter {


    SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Autowired
    FialAuthenticationHandller fialAuthenticationHandller;

    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (StringUtils.equals("/authentication/form",httpServletRequest.getRequestURI())
                 &&StringUtils.endsWithIgnoreCase("post",httpServletRequest.getMethod())){
           try {
               validCode(httpServletRequest);
           }catch (ValidCodeException e){
               fialAuthenticationHandller.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return;
           }
            //校验业务逻辑
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    /**
     * @param request
     * @throws ServletRequestBindingException
     */
    private void validCode(HttpServletRequest request) throws ServletRequestBindingException,ValidCodeException {

        Object code = sessionStrategy.getAttribute(new ServletWebRequest(request), "code");
        String codeRequest = ServletRequestUtils.getStringParameter(request, "imageCode");

        if (StringUtils.isBlank(codeRequest)){
            throw  new ValidCodeException("验证码不能为空");
        }
        if (code==null){
            throw  new ValidCodeException("验证码输入有误");
        }
        ImageCode imageCode = (ImageCode)code;
        if (!StringUtils.equalsAnyIgnoreCase(imageCode.getCode(),codeRequest)){
            throw  new ValidCodeException("验证码不正确");
        }
        if (imageCode.idExpire()){
            throw new ValidCodeException("验证码已经过期");
        }


    }
}
